{% load sentry_assets %}
{% load sentry_trace %}

<meta name="sentry-trace" content="{% get_sentry_trace %}">
<meta name="baggage" content="{% get_sentry_baggage %}">

{% script %}
<script type="text/javascript">
  function __preloadData() {
    if (!window.__initialData.user) {
      // Don't send requests if there is no logged in user.
      return;
    }
    var slug = window.__initialData.lastOrganization;
    if (!slug && window.__initialData.customerDomain) {
      slug = window.__initialData.customerDomain.subdomain;
    }
    var host = '';
    if (window.__initialData.links && window.__initialData.links.regionUrl !== window.__initialData.links.sentryUrl) {
      var host = window.__initialData.links.regionUrl;
    }

    function promiseRequest(url) {
      return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.setRequestHeader("sentry-trace", window.__initialData.initialTrace.sentry_trace);
        xhr.setRequestHeader("baggage", window.__initialData.initialTrace.baggage);
        xhr.withCredentials = true;
        xhr.onload = function () {
          try {
            this.status >= 200 && this.status < 300
              ? resolve([JSON.parse(xhr.response), this.statusText, xhr])
              : reject([this.status, this.statusText]);
          } catch (e) {
            reject();
          }
        };
        xhr.onerror = function () {
          reject([this.status, this.statusText]);
        };
        xhr.send();
      });
    }

    function makeUrl(suffix) {
      return host + '/api/0/organizations/' + slug + suffix;
    }

    var preloadPromises = {orgSlug: slug};
    window.__sentry_preload = preloadPromises;

    if (!slug) {
      return;
    }

    preloadPromises.organization = promiseRequest(makeUrl('/?detailed=0'));
    preloadPromises.projects = promiseRequest(
      makeUrl('/projects/?all_projects=1&collapse=latestDeploys&collapse=unusedFeatures')
    );
    preloadPromises.teams = promiseRequest(makeUrl('/teams/'));
  }

  try {
    __preloadData();
  } catch (_) {}
</script>
{% endscript %}
